<?php

/**
 * Aihexpenses Controller
 *
 * PHP version 5
 *
 * @category Controller
 * @package  Croogo
 * @version  1.0
 * @author   Tran Van Dung <dungtv@ic-t.info>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://www.croogo.org
 */
class PaymentschedulesController extends AppController {

    /**
     * Controller name
     *
     * @var string
     * @access public
     */
    public $name = 'Paymentschedules';

    /**
     * Models used by the Controller
     *
     * @var array
     * @access public
     */
    public $uses = array('Paymentschedule', 'Placementdetailt', 'Accountresume', 'Aihcontact', 'Market', 'Paymentrecord');

    /**
     * Helpers used by the Controller
     *
     * @var array
     * @access public
     */
    public $helpers = array('Text', 'Html', 'Js');
    protected $paginate = array(
        'limit' => 10,
    );

    /**
     * Before executing controller actions
     *
     * @return void
     * @access public
     */
    public function beforeFilter() {
        parent::beforeFilter();
        if ($this->action == 'add' || $this->action == 'edit' || $this->action == 'admin_add' || $this->action == 'admin_edit') {
            $this->Security->validatePost = false;
        }
    }

    /**
     * Admin index
     *
     * @return void
     * @access public
     */
    public function admin_index() {
        $this->set('title_for_layout', __('PAYMENT SCHEDULE LIST'));

        $scriptWindowMsg = $this->windowMsg();
        $this->set('scriptWindowMsg', $scriptWindowMsg);

        $script = $this->getcontactJS();
        $this->set('script', $script);

        $scriptSearchBox = $this->scriptSearchBox();
        $this->set('scriptSearchBox', $scriptSearchBox);

        $this->Paymentschedule->recursive = 0;
        $this->paginate['Paymentschedule']['order'] = 'Paymentschedule.id ASC';

        $this->set('paymentschedules', $this->paginate());
    }

    public function admin_search() {
        $this->set('title_for_layout', __('PAYMENT SCHEDULE SEARCH'));

        $scriptWindowMsg = $this->windowMsg();
        $this->set('scriptWindowMsg', $scriptWindowMsg);

        $script = $this->getcontactJS();
        $this->set('script', $script);

        $scriptSearchBox = $this->scriptSearchBox();
        $this->set('scriptSearchBox', $scriptSearchBox);

        $q = $this->params['named']['q'];
        $paid = $this->params['named']['paid'];
        $this->set('q', $q);
        $this->set('paid', $paid);

        $this->Paymentschedule->recursive = 0;
        if ($q == 'all') {
            if ($paid == 'true') {
                $this->paginate['Paymentschedule']['conditions'] = array('Paymentschedule.paid' => 1);
            }
        } else {
            if ($paid == 'true') {
                $this->paginate['Paymentschedule']['conditions'] = array('Paymentschedule.paid' => 1, 'OR' => array(
                        'Paymentschedule.payer_name LIKE' => '%' . $q . '%',
                        'Paymentschedule.refid_edit LIKE' => '%' . $q . '%',
                        ));
            } else {
                $this->paginate['Paymentschedule']['conditions'] = array('OR' => array(
                        'Paymentschedule.payer_name LIKE' => '%' . $q . '%',
                        'Paymentschedule.refid_edit LIKE' => '%' . $q . '%',
                        ));
            }
        }
        $this->paginate['Paymentschedule']['order'] = 'Paymentschedule.id ASC';

        $this->set('paymentschedules', $this->paginate());
    }

    /**
     * Admin add
     *
     * @return void
     * @access public
     */
    public function admin_add() {
        $this->set('title_for_layout', __('PAYMENT SCHEDULE DETAIL'));

        $script = $this->jsProcess();
        $this->set('script', $script);

        $placementscript = $this->getPlacementJS();
        $this->set('placementscript', $placementscript);

        if (!empty($this->request->data)) {
            $this->request->data['Paymentschedule']['paid_date'] = date('Y-m-d', strtotime($this->request->data['Paymentschedule']['paid_date']));
            if ($this->request->data['Paymentschedule']['paid']) {
                $this->request->data['Paymentschedule']['paid_amount'] = $this->request->data['Paymentschedule']['PaymentscheduleAmount1'] + $this->request->data['Paymentschedule']['Paidamount'];
                $this->request->data['Paymentschedule']['exchange_to'] = $this->request->data['exchangeto'];
            } else {
                $this->request->data['Paymentschedule']['paid_date'] = '';
                $this->request->data['Paymentschedule']['paid_amount'] = 0;
                $this->request->data['Paymentschedule']['exchange'] = '';
                $this->request->data['Paymentschedule']['exchange_to'] = '';
            }
            $paymentschedule = $this->Paymentschedule->find('first', array('fields' => array('Paymentschedule.id'), 'conditions' => array('Paymentschedule.refid' => $this->request->data['Paymentschedule']['Paymentschedule'])));
            $this->request->data['Paymentschedule']['id'] = $paymentschedule['Paymentschedule']['id'];
            //save placement for market



            if ($this->Paymentschedule->save($this->request->data)) {

                $Paymentdata = array(
                    'payment_id' => $this->Paymentschedule->id,
                    'payer' => $this->request->data['payer_name'],
                    'payee' => $this->request->data['payee_name'],
                    'amount' => $this->request->data['Paymentschedule']['PaymentscheduleAmount1'],
                    'currency' => $this->request->data['currency_name'],
                    'exchange' => $this->request->data['Paymentschedule']['exchange'],
                    'exchange_to' => $this->request->data['exchangeto'],
                    'usd_amount' => ($this->request->data['Paymentschedule']['exchange'] != '') ? ($this->request->data['Paymentschedule']['PaymentscheduleAmount1'] / $this->request->data['Paymentschedule']['exchange']) : '',
                    'date' => $this->request->data['Paymentschedule']['paid_date'],
                );
                if ($this->request->data['Paymentschedule']['paid']) {
                    if ($this->request->data['Paymentschedule']['PaymentscheduleAmount1'] > 0) {
                        $this->Paymentrecord->save($Paymentdata);
                    }
                } else {
                    $ids = $this->Paymentrecord->find('all', array(
                        'fields' => array('Paymentrecord.id'),
                        'conditions' => array(
                            'payment_id' => $this->Paymentschedule->id,
                        ),
                            ));

                    foreach ($ids as $obj) {
                        $id = $obj['Paymentrecord']['id'];
                        $deldata = array(
                            'id' => $id,
                            'deleted' => 1,
                        );
                        $this->Paymentrecord->save($deldata);
                    }
                }

                //save placement for market
                $dataplacement = array();
                $placementdetail = $this->Paymentschedule->find('first', array('conditions' => array('Paymentschedule.id' => $this->request->data['Paymentschedule']['id'],)));
                $arrs = $this->Paymentschedule->decodeData($placementdetail['Paymentschedule']['markets']);
                foreach ($arrs as $key => $value) {
                    $checkpaidid = 'chk-payment-' . $key;
                    $dateid = 'paid_placement_date_' . $key;
                    $temp['paid'] = $this->request->data[$checkpaidid];
                    $temp['paid_date'] = date('Y-m-d', strtotime($this->request->data[$dateid]));
                    $dataplacement[$key] = $temp;
                    //'id' => $placementdetail['Placementdetailt']['id'],
                }
                //php_debug(json_encode($dataplacement));
                $this->Paymentschedule->save(array('id' => $placementdetail['Paymentschedule']['id'], 'placement_paid' => json_encode($dataplacement)));

                //save placement for AIH
                //$placementdetail = $this->Paymentschedule->find('first', array('fields' => array('Paymentschedule.id'), 'conditions' => array('Paymentschedule.refid' => $this->request->data['PaymentschedulePaymentschedule'],)));

                $data = array(
                    'id' => $placementdetail['Paymentschedule']['id'],
                    'paid_to_aih' => $this->request->data['chk_payment_aih'],
                    'paid_to_aih_date' => date('Y-m-d', strtotime($this->request->data['paid_aih_placement_date'])),
                );
                //php_debug($data);
                $this->Paymentschedule->save($data);
                //

                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The Expense could not be saved. Please, try again.'), 'default', array('class' => 'error'));
            }
        }
        $accountresumes = $this->Accountresume->find('list', array('fields' => array('Accountresume.refid', 'Accountresume.refid_edit'), 'order' => array('Accountresume.refid_edit ASC'),));
        $this->set(compact('accountresumes'));
    }

    /**
     * Admin edit
     *
     * @param int $id 
     * @return void
     * @access public
     */
    public function admin_edit($id = null) {
        $this->set('title_for_layout', __('PAYMENT SCHEDULE DETAIL'));

        $script = $this->jsProcess();
        $this->set('script', $script);

        $placementscript = $this->getPlacementJS();
        $this->set('placementscript', $placementscript);

        if (!$id && empty($this->request->data)) {
            $this->Session->setFlash(__('Invalid ID'), 'default', array('class' => 'error'));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->request->data)) {
            $this->request->data['Paymentschedule']['paid_date'] = date('Y-m-d', strtotime($this->request->data['Paymentschedule']['paid_date']));
            if ($this->request->data['Paymentschedule']['paid']) {
                $this->request->data['Paymentschedule']['paid_amount'] = $this->request->data['Paymentschedule']['PaymentscheduleAmount1'] + $this->request->data['Paymentschedule']['Paidamount'];
                $this->request->data['Paymentschedule']['exchange_to'] = $this->request->data['exchangeto'];
            } else {
                $this->request->data['Paymentschedule']['paid_date'] = '';
                $this->request->data['Paymentschedule']['paid_amount'] = 0;
                $this->request->data['Paymentschedule']['exchange'] = '';
                $this->request->data['Paymentschedule']['exchange_to'] = '';
            }
            //php_debug($this->request->data);
            //php_debug($this->request->data);
            if ($this->Paymentschedule->save($this->request->data)) {
                //php_debug($this->request->data);
                $Paymentdata = array(
                    'payment_id' => $this->request->data['Paymentschedule']['id'],
                    'payer' => $this->request->data['payer_name'],
                    'payee' => $this->request->data['payee_name'],
                    'amount' => $this->request->data['Paymentschedule']['PaymentscheduleAmount1'],
                    'currency' => $this->request->data['currency_name'],
                    'exchange' => $this->request->data['Paymentschedule']['exchange'],
                    'exchange_to' => $this->request->data['exchangeto'],
                    'usd_amount' => ($this->request->data['Paymentschedule']['exchange'] != '') ? ($this->request->data['Paymentschedule']['PaymentscheduleAmount1'] / $this->request->data['Paymentschedule']['exchange']) : '',
                    'date' => $this->request->data['Paymentschedule']['paid_date'],
                );
                if ($this->request->data['Paymentschedule']['paid']) {
                    //php_debug($Paymentdata);
                    if ($this->request->data['Paymentschedule']['PaymentscheduleAmount1'] > 0) {
                        $this->Paymentrecord->save($Paymentdata);
                    }
                } else {
                    $ids = $this->Paymentrecord->find('all', array(
                        'fields' => array('Paymentrecord.id'),
                        'conditions' => array(
                            'payment_id' => $this->request->data['Paymentschedule']['id'],
                        ),
                            ));

                    foreach ($ids as $obj) {
                        $id = $obj['Paymentrecord']['id'];
                        $deldata = array(
                            'id' => $id,
                            'deleted' => 1,
                        );
                        $this->Paymentrecord->save($deldata);
                    }
                }

                //save placement for market
                $dataplacement = array();
                $placementdetail = $this->Paymentschedule->find('first', array('conditions' => array('Paymentschedule.id' => $this->request->data['Paymentschedule']['id'],)));
                $arrs = $this->Paymentschedule->decodeData($placementdetail['Paymentschedule']['markets']);
                foreach ($arrs as $key => $value) {
                    $checkpaidid = 'chk-payment-' . $key;
                    $dateid = 'paid_placement_date_' . $key;
                    $temp['paid'] = $this->request->data[$checkpaidid];
                    $temp['paid_date'] = date('Y-m-d', strtotime($this->request->data[$dateid]));
                    $dataplacement[$key] = $temp;
                    //'id' => $placementdetail['Placementdetailt']['id'],
                }
                //php_debug(json_encode($dataplacement));
                $this->Paymentschedule->save(array('id' => $placementdetail['Paymentschedule']['id'], 'placement_paid' => json_encode($dataplacement)));

                //save placement for AIH
                //$placementdetail = $this->Paymentschedule->find('first', array('fields' => array('Paymentschedule.id'), 'conditions' => array('Paymentschedule.refid' => $this->request->data['PaymentschedulePaymentschedule'],)));

                $data = array(
                    'id' => $placementdetail['Paymentschedule']['id'],
                    'paid_to_aih' => $this->request->data['chk_payment_aih'],
                    'paid_to_aih_date' => date('Y-m-d', strtotime($this->request->data['paid_aih_placement_date'])),
                );
                //php_debug($data);
                $this->Paymentschedule->save($data);
                //

                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The Payment could not be saved. Please, try again.'), 'default', array('class' => 'error'));
            }
        }
        if (empty($this->request->data)) {
            $this->request->data = $this->Paymentschedule->read(null, $id);
            $ref_edit = $this->Accountresume->find('first', array(
                'conditions' => array('Accountresume.refid' => $this->request->data['Paymentschedule']['accountresume_id'])));
            $this->request->data['Paymentschedule']['refid_edit'] = $ref_edit['Accountresume']['refid_edit'];
        }
    }

    /**
     * Admin delete
     *
     * @param int $id 
     * @return void
     * @access public
     */
    public function admin_delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id'), 'default', array('class' => 'error'));
            $this->redirect(array('action' => 'index'));
        }

        $aihexpense = $this->Paymentschedule->find('first', array(
            'conditions' => array(
                'id' => $id,
            ),
                ));
        if (isset($aihexpense['Paymentschedule'])) {
            if ($this->Paymentschedule->delete($id)) {
                //$this->Session->setFlash(__('Expense deleted'), 'default', array('class' => 'success'));
                $this->redirect(array('action' => 'index'));
            }
        } else {
            $this->Session->setFlash(__('Invalid ID '), 'default', array('class' => 'error'));
            $this->redirect(array('action' => 'index'));
        }
    }

    public function admin_getvalue($id = null) {

        $this->layout = 'ajax';
        $success = false;
        if ($id != '' || $id != 'undefined') {
            $paymentschedule = $this->Paymentschedule->find('first', array('conditions' => array('Paymentschedule.refid' => $id)));
            if ($paymentschedule) {
                //$payer = $this->Aihcontact->find('first', array('conditions' => array('Aihcontact.id' => $paymentschedule['Paymentschedule']['payer'])));
                $success = true;
                $paid_date = '';
                if ($paymentschedule['Paymentschedule']['paid_date'] != '0000-00-00') {
                    $paid_date = date('m/d/Y', strtotime($paymentschedule['Paymentschedule']['paid_date']));
                }
                $success = $this->Paymentschedule->encodeData(array(
                    'success' => $success,
                    'broker_date' => date('m/d/Y', strtotime($paymentschedule['Paymentschedule']['broker_date'])),
                    //'payer' => $payer['Aihcontact']['name'],
                    'payer' => $paymentschedule['Paymentschedule']['payer_name'],
                    'payee' => $paymentschedule['Paymentschedule']['payee'],
                    'broker_amount' => $paymentschedule['Paymentschedule']['broker_amount'],
                    'currency' => $paymentschedule['Paymentschedule']['currency'],
                    'exchange' => $paymentschedule['Paymentschedule']['exchange'],
                    'exchange_to' => $paymentschedule['Paymentschedule']['exchange_to'],
                    'paid' => $paymentschedule['Paymentschedule']['paid'],
                    'paid_date' => $paid_date,
                    'paid_amount' => $paymentschedule['Paymentschedule']['paid_amount'],
                    'account_name' => $paymentschedule['Paymentschedule']['account_name'],
                    'payment_desc' => $paymentschedule['Paymentschedule']['payment_desc'],
                        ), array('json' => true, 'trim' => false));
            } else {
                $success = $this->Paymentschedule->encodeData(array('success' => $success));
            }
        } else {
            $success = $this->Paymentschedule->encodeData(array('success' => $success));
        }
        $this->set('success', $success);
    }

    public function admin_getpaymentdetail($id = '') {

        $this->layout = 'ajax';
        $success = false;
        if ($id != '' || $id != 'undefined') {
            $paymentschedule = $this->Paymentschedule->find('list', array('fields' => array('Paymentschedule.refid', 'Paymentschedule.refid'), 'conditions' => array('Paymentschedule.accountresume_id' => $id,)));
            if ($paymentschedule) {
                $success = true;
                $success = $this->Paymentschedule->encodeData(array('success' => $success, 'payments' => $paymentschedule), array('json' => true, 'trim' => false));
            } else {
                $success = $this->Paymentschedule->encodeData(array('success' => $success));
            }
        } else {
            $success = $this->Paymentschedule->encodeData(array('success' => $success));
        }
        $this->set('success', $success);
    }

    public function admin_getplacementdetailtoaih($id = '') {

        $this->layout = 'ajax';
        $success = false;
        if ($id != '') {
            $placementdetail = $this->Paymentschedule->find('first', array('conditions' => array('Paymentschedule.refid' => $id,)));
            if ($placementdetail) {
                $success = true;
                $paid_date = '';
                $placementdetail['Paymentschedule']['contact_amount'] = number_format($placementdetail['Paymentschedule']['aih_amount'], 2) . ' ' . $placementdetail['Paymentschedule']['currency'];
                if ($placementdetail['Paymentschedule']['exchange'] != '') {
                    $converted_amount = number_format($placementdetail['Paymentschedule']['aih_amount'] / $placementdetail['Paymentschedule']['exchange'], 2) . ' ' . $placementdetail['Paymentschedule']['exchange_to'];
                } else {
                    $converted_amount = '';
                }
                if ($placementdetail['Paymentschedule']['paid_to_aih_date'] == '' || $placementdetail['Paymentschedule']['paid_to_aih_date'] == '0000-00-00') {
                    $paid_date = '';
                } else {
                    $paid_date = date('m/d/Y', strtotime($placementdetail['Paymentschedule']['paid_to_aih_date']));
                }

                $success = $this->Paymentschedule->encodeData(array(
                    'success' => $success,
                    'aih_date' => date('m/d/Y', strtotime($placementdetail['Paymentschedule']['aih_date'])),
                    'amount' => $placementdetail['Paymentschedule']['contact_amount'],
                    'rawamount' => $placementdetail['Paymentschedule']['aih_amount'],
                    'converted_amount' => $converted_amount,
                    'paid_date' => $paid_date,
                    'paid' => $placementdetail['Paymentschedule']['paid_to_aih'],
                        ), array('json' => true, 'trim' => false));
            } else {
                $success = $this->Paymentschedule->encodeData(array('success' => $success));
            }
        } else {
            $success = $this->Paymentschedule->encodeData(array('success' => $success));
        }
        $this->set('success', $success);
    }

    public function admin_getplacementdetailt($id = '') {

        $this->layout = 'ajax';
        $success = false;
        if ($id != '' || $id != 'undefined') {
            $placementdetail = $this->Paymentschedule->find('first', array('conditions' => array('Paymentschedule.refid' => $id,)));
            $arrs = $this->Paymentschedule->decodeData($placementdetail['Paymentschedule']['markets']);
            $arrspaid = $this->Paymentschedule->decodeData($placementdetail['Paymentschedule']['placement_paid']);
            //php_debug($arrspaid);
            // repair data
            $temps = array();
            foreach ($arrs as $key => $arr) {

                $arr['contactname'] = $arr[0];
                $arr['contact_id'] = $key;
                $arr['refid'] = $key;
                $arr['contact_amount'] = number_format($arr[3], 2) . ' ' . $placementdetail['Paymentschedule']['currency'];
                $arr['rawamount'] = $arr[3];
                if ($placementdetail['Paymentschedule']['exchange'] != '') {
                    $arr['converted_amount'] = number_format($arr[3] / $placementdetail['Paymentschedule']['exchange'], 2) . ' ' . $placementdetail['Paymentschedule']['exchange_to'];
                } else {
                    $arr['converted_amount'] = '';
                }
                if (empty($arrspaid)) {
                    $arr['paid'] = false;
                    if ($arr[2] == '0000-00-00') {
                        $arr['paid_date'] = '';
                    } else {
                        $arr['paid_date'] = date('m/d/Y', strtotime($arr[2]));
                    }
                } else {
                    $arr['paid'] = $arrspaid[$key]['paid'];
                    $arr['paid_date'] = date('m/d/Y', strtotime($arrspaid[$key]['paid_date']));
                }

                $temps[] = $arr;
            }

            if ($temps) {
                $success = true;
                $success = $this->Paymentschedule->encodeData(array(
                    'success' => $success,
                    'data' => $temps
                        ), array('json' => true, 'trim' => false));
            } else {
                $success = $this->Paymentschedule->encodeData(array('success' => $success));
            }
        } else {
            $success = $this->Paymentschedule->encodeData(array('success' => $success));
        }
        $this->set('success', $success);
        $this->set('id', $id);
    }

    public function admin_report_revenue_commission($ids = null) {
        $this->layout = 'admin_report';
        $this->set('title_for_layout', __('AIH REVENUE COMMISSION REPORT'));

        $this->Paymentschedule->recursive = 0;
        $this->paginate['Paymentschedule']['conditions'] = array('Paymentschedule.id' => explode('-', $ids));
        $this->paginate['Paymentschedule']['order'] = 'Paymentschedule.id ASC';

        $this->set('paymentschedules', $this->paginate());
        $this->set('ids', $ids);
    }

    public function admin_report_open_trade_account($ids = null) {
        $this->layout = 'admin_report';
        $this->set('title_for_layout', __('OPEN TRADE ACCOUNT'));
        $this->set('ids', $ids);
        $scriptFilter = $this->scriptFilter();
        $this->set('scriptFilter', $scriptFilter);
        $to = 0;
        $selected_to = '';
        $selected_from = '';
        if (isset($this->params['named']['to']) && $this->params['named']['to'] == 1) {
            $to = 1;
            $selected_to = 'selected="selected"';
            $selected_from = '';
        } else {
            $selected_to = '';
            $selected_from = 'selected="selected"';
        }

        $this->set('selected_to', $selected_to);
        $this->set('selected_from', $selected_from);

        $proccessed = -1;
        $selected_proccessed = '';
        $selected_outstanding = '';
        if (isset($this->params['named']['proccessed'])) {
            if ($this->params['named']['proccessed'] == 1) {
                $proccessed = 1;
                $selected_proccessed = 'selected="selected"';
                $selected_outstanding = '';
            } elseif ($this->params['named']['proccessed'] == 0) {
                $proccessed = 0;
                $selected_proccessed = '';
                $selected_outstanding = 'selected="selected"';
            }
        }
        $this->set('selected_proccessed', $selected_proccessed);
        $this->set('selected_outstanding', $selected_outstanding);

        $this->set('to', $to);
        $this->set('proccessed', $proccessed);
        $this->set('link_to', '&to=' . $to);
        $this->set('link_proccessed', '&proccessed=' . $proccessed);

        $this->Paymentschedule->recursive = 0;
        if ($proccessed > -1) {
            $this->paginate['Paymentschedule']['conditions'] = array('Paymentschedule.id' => explode('-', $ids), 'Paymentschedule.paid' => $proccessed);
        } else {
            $this->paginate['Paymentschedule']['conditions'] = array('Paymentschedule.id' => explode('-', $ids));
        }
        $this->paginate['Paymentschedule']['order'] = 'Paymentschedule.id ASC';

        $this->set('paymentschedules', $this->paginate());
    }

    public function admin_report_payment_tracking($ids = null) {
        $this->layout = 'admin_report';
        $this->set('title_for_layout', __('AIH PAYMENT TRACKING REPORT'));

        $arrayid = explode('-', $ids);
        $arrid = array();

        foreach ($arrayid as $id) {
            $placementdetail = $this->Paymentschedule->find('first', array('conditions' => array('Paymentschedule.id' => $id,)));
            $arrs = $this->Paymentschedule->decodeData($placementdetail['Paymentschedule']['markets']);
            $arrspaid = $this->Paymentschedule->decodeData($placementdetail['Paymentschedule']['placement_paid']);
            //php_debug($arrspaid);
            // repair data
            $temps = array();
            $aihend = array();
            foreach ($arrs as $key => $arr['Placementdetailt']) {
                $arr['Placementdetailt']['contact_name'] = $arr['Placementdetailt'][0];
                $arr['Placementdetailt']['paymentid'] = $id;
                $arr['Placementdetailt']['paymentrefid'] = $placementdetail['Paymentschedule']['refid'];
                $arr['Placementdetailt']['currency'] = $placementdetail['Paymentschedule']['currency'];
                $accid = $this->Accountresume->find('first', array('conditions' => array('Accountresume.refid' => $placementdetail['Paymentschedule']['accountresume_id'])));
                $arr['Placementdetailt']['accid'] = $accid['Accountresume']['id'];
                $arr['Placementdetailt']['refid_edit'] = $placementdetail['Paymentschedule']['refid_edit'];
                $arr['Placementdetailt']['paid_amount'] = $placementdetail['Paymentschedule']['paid_amount'];
                $arr['Placementdetailt']['aih_amount'] = $placementdetail['Paymentschedule']['aih_amount'];
                if ($placementdetail['Paymentschedule']['paid_amount'] == $placementdetail['Paymentschedule']['broker_amount']) {
                    $arr['Placementdetailt']['alltoaih'] = 1;
                } else {
                    $arr['Placementdetailt']['alltoaih'] = 0;
                }
                $arr['Placementdetailt']['paid_to_aih'] = $placementdetail['Paymentschedule']['paid_to_aih'];
                $arr['Placementdetailt']['refid'] = $key;
                $arr['Placementdetailt']['broker_amount'] = $placementdetail['Paymentschedule']['broker_amount'];
                ;
                $arr['Placementdetailt']['contact_amount'] = number_format($arr['Placementdetailt'][3], 2) . ' ' . $placementdetail['Paymentschedule']['currency'];

                if (empty($arrspaid)) {
                    $arr['Placementdetailt']['paid'] = false;
                    if ($arr['Placementdetailt'][2] == '0000-00-00') {
                        $arr['Placementdetailt']['paid_date'] = '';
                    } else {
                        $arr['Placementdetailt']['paid_date'] = date('m/d/Y', strtotime($arr['Placementdetailt'][2]));
                    }
                } else {
                    $arr['Placementdetailt']['paid'] = $arrspaid[$key]['paid'];
                    if ($arr['Placementdetailt']['paid'] == 'on') {
                        $arr['Placementdetailt']['paid'] = 1;
                    } else {
                        $arr['Placementdetailt']['paid'] = 0;
                    }
                    $arr['Placementdetailt']['paid_date'] = date('m/d/Y', strtotime($arrspaid[$key]['paid_date']));
                }

                $temps[] = $arr;
            }
            $arr['Placementdetailt']['contact_name'] = 'AIH Commission';
            $arr['Placementdetailt']['contact_amount'] = $placementdetail['Paymentschedule']['aih_amount'];
            $aihend = $arr;
            $temps[] = $aihend;
            $a[] = $temps;
        }
//        php_debug($a);
        $this->set('trakingreports', $a);
        $this->set('ids', $ids);
    }

    public function admin_report_installment_tracking($ids = null) {
        $this->layout = 'admin_report';
        $this->set('title_for_layout', __('AIH INSTALLMENT TRACKING REPORT'));

        $arrayid = explode('-', $ids);
        $arrid = array();

        foreach ($arrayid as $id) {
            $resumeid = $this->Paymentschedule->find('first', array('fields' => array('Paymentschedule.accountresume_id'), 'conditions' => array('Paymentschedule.id' => $id)));
            if (!in_array($resumeid['Paymentschedule']['accountresume_id'], $arrid)) {
                $arrid[] = $resumeid['Paymentschedule']['accountresume_id'];
            }
        }
        foreach ($arrid as $obj) {
            $temp = array();

            $paymentschedulesarr = $this->Paymentschedule->find('all', array(
                'conditions' => array(
                    'Paymentschedule.accountresume_id' => $obj,
                ),
                    )
            );
            $i = 0;
            foreach ($paymentschedulesarr as $paymentschedule) {
                $i++;
                $paymentschedule['Paymentschedule']['installment'] = $i;
                $paymentschedule['Paymentschedule']['outstanding'] = $paymentschedule['Paymentschedule']['broker_amount'] - $paymentschedule['Paymentschedule']['paid_amount'];

                if ($paymentschedule['Paymentschedule']['outstanding'] == 0) {
                    $paymentschedule['Paymentschedule']['alltoaih'] = 1;
                } else {
                    $paymentschedule['Paymentschedule']['alltoaih'] = 0;
                }

                $arrs = $this->Paymentschedule->decodeData($paymentschedule['Paymentschedule']['markets']);
                $arrspaid = $this->Paymentschedule->decodeData($paymentschedule['Paymentschedule']['placement_paid']);

                $paymentschedule['Paymentschedule']['arrmarket'] = $arrs;
                $paymentschedule['Paymentschedule']['arrmarketpaid'] = $arrspaid;

                $accid = $this->Accountresume->find('first', array(
                    'conditions' => array('Accountresume.refid' => $paymentschedule['Paymentschedule']['accountresume_id'])));
                $paymentschedule['Paymentschedule']['accid'] = $accid['Accountresume']['id'];

                $temp[] = $paymentschedule;
            }

            $a[] = $temp;
        }
        //php_debug($a);
        $this->set('trakingreports', $a);
        $this->set('ids', $ids);
    }

    public function admin_report_payment_schedules($ids = null) {
        $this->layout = 'admin_report_payment_tracking';
        $this->set('title_for_layout', __('AIH PAYMENT SCHEDULES REPORT'));

        $paymentschedules = $this->Paymentschedule->find('all', array(
            'conditions' => array('Paymentschedule.id' => explode('-', $ids))
                )
        );

        $this->set('paymentschedules', $paymentschedules);
        $this->set('ids', $ids);
    }

    public function admin_payment_records($id = null) {
        $this->layout = 'admin_report_payment_record';
        $this->set('title_for_layout', __('PAYMENT RECORDS PER INSTALLMENT'));

        $paymentrecords = $this->Paymentrecord->find('all', array(
            'conditions' => array(
                'Paymentrecord.payment_id' => $id,
                'Paymentrecord.deleted' => 0,
                ))
        );
        $total = $this->Paymentschedule->find('first', array(
            'fields' => array('Paymentschedule.broker_amount'), 'conditions' => array('Paymentschedule.id' => $id)
                )
        );
        foreach ($paymentrecords as $paymentrecord) {
            $temp[] = $paymentrecord;
        }
        $this->set('paymentrecords', $temp);
        $this->set('total_amount', $total['Paymentschedule']['broker_amount']);
    }

    public function jsProcess() {
        $output = "
            $(function() {
                $('#PaymentschedulePaid').click(function() {
                    if($(this).is(':checked')) {
                        $('#PaymentschedulePaidDate').attr('style', 'display:inline');
                    } else {
                        $('#PaymentschedulePaidDate').attr('style', 'display:none');
                    }
                });
                $('.sel-date-paid').datepicker({ changeYear: true });
                $('#PaymentschedulePaymentschedule').change(function() {
                    $.getJSON('" . Router::url('/admin/paymentschedules/getvalue/', true) . "'+$(this).val(), function(data) {
                        if(data.success) {
                            $('#PaymentscheduleDate').html(data.broker_date);
                            $('#PaymentschedulePayer').html(data.payer);
                            $('#PaymentschedulePayee').html(data.payee);
                            $('#payername').val(data.payer);
                            $('#payeename').val(data.payee);
                            $('#currencyname').val(data.currency);
                            $('#PaymentscheduleAmount').val(data.broker_amount - data.paid_amount);
                            $('#PaymentscheduleAmount1').val(data.broker_amount - data.paid_amount);
                            if(data.exchange* 1 > 0){
                                $('#spanpaidamount').html(data.paid_amount/data.exchange);
                            }else{
                                $('#spanpaidamount').html(data.paid_amount);
                            }
                            $('#spanpaidamount').formatCurrency();
                            $('#paidamount').val(data.paid_amount);
                            $('#PaymentscheduleAmount').formatCurrency();
                            if(data.exchange* 1 > 0){
                                if(data.exchange_to != null){
                                    $('#paidamountcurrency').html(data.exchange_to);
                                }else{
                                    $('#paidamountcurrency').html('USD');
                                }
                                if(data.exchange_to == 'EURO'){
                                    $('#exchangeto').removeAttr('selected').find('option:contains(\"EURO\")').attr('selected','selected');
                                }else{
                                    $('#exchangeto').removeAttr('selected').find('option:contains(\"USD\")').attr('selected','selected');
                                }
                            }else{
                                $('#paidamountcurrency').html(data.currency);
                            }
                            $('#PaymentscheduleCurrency').html(data.currency);
                            $('#PaymentscheduleAccountName').val(data.account_name);
                            $('#PaymentschedulePaymentDesc').val(data.payment_desc);
                            $('#PaymentscheduleExchange').val(data.exchange);
                            if(data.exchange * 1 > 0) {
                                $('#exchangeUSD').html(parseFloat(data.broker_amount/data.exchange)).formatCurrency();
                            }
                            if(data.paid_date != ''){
                                $('#PaymentschedulePaidDate').val(data.paid_date);
                            }else{
                                //$('#PaymentschedulePaidDate').val(data.broker_date);
                                var d = new Date();
                                var twoDigitMonth = ((d.getMonth().length+1) === 1)? (d.getMonth()+1) : '0' + (d.getMonth()+1);
                                var todaystring = twoDigitMonth + '/' + d.getDate() + '/' + d.getFullYear();
                                $('#PaymentschedulePaidDate').val(todaystring);
                            }
                            if(data.paid){
                                $('#PaymentschedulePaid').attr('checked', true);
                                $('#PaymentschedulePaidDate').attr('style', 'display:inline');
                            }else{
                                $('#PaymentschedulePaid').removeAttr('checked');
                                $('#PaymentschedulePaidDate').attr('style', 'display:none');
                            }
                            if(data.broker_amount == data.paid_amount){
                                $('#PaymentscheduleAmount').attr('readonly', 'readonly');
                            }else{
                                $('#PaymentscheduleAmount').removeAttr('readonly');
                            }
                            if($('#PaymentscheduleExchange').val() * 1 > 0) {
                                $('#exchangeUSD').html(parseFloat($('#PaymentscheduleAmount1').val()/$('#PaymentscheduleExchange').val())).formatCurrency();
                            }
                            
                        } else {
                            // error
                        }
                    });
                });
                $('#PaymentscheduleExchange').focusout(function() {
                    if($('#PaymentscheduleExchange').val() * 1 > 0) {
                        $('#exchangeUSD').html(parseFloat($('#PaymentscheduleAmount1').val()/$('#PaymentscheduleExchange').val())).formatCurrency();
                        $('#convertedtoaih').html(parseFloat($('#rawplacementtoaihamout').val())/$('#PaymentscheduleExchange').val()).formatCurrency();
                        $('#convertedtoaih').append(' ' + $('#exchangeto').val());
                        $('input.containrefid').each(function(i) {
                            //alert(i + ': ' + $(this).val());
                            $('#convertedAmoutPlacement' + $(this).val()).html(parseFloat($('#raw-placement-amount-' + $(this).val()).val()/$('#PaymentscheduleExchange').val())).formatCurrency();
                            $('#convertedAmoutPlacement' + $(this).val()).append(' ' + $('#exchangeto').val());
                        });
                    }else if($('#PaymentscheduleExchange').val() == ''){
                    }else{
                        $('#PaymentscheduleExchange').focus();
                        alert('Exchange rate is invalid!');   
                    }
                });
                
                var alertamout            
                $('#PaymentscheduleAmount').focus(function () {
                    alertamout = $(this).val();
                }).change(function() {
                    $(this).formatCurrency();
                    //var alertamout = $(this).val()
                    var amount = Number($(this).val().replace(/[^0-9\.]+/g,''));
                    if(amount > $('#PaymentscheduleAmount1').val()){
                        alert('Amount is invalid (can not be greater than ' + alertamout + ')');
                        $(this).val($('#PaymentscheduleAmount1').val());
                        amount = Number($('#PaymentscheduleAmount1').val().replace(/[^0-9\.]+/g,''));
                    }
                    if(amount * 1 > 0) {
                        $('#PaymentscheduleAmount1').val(amount);
                        $(this).formatCurrency();
                        if($('#PaymentscheduleExchange').val() * 1 > 0) {
                            $('#exchangeUSD').html(parseFloat($('#PaymentscheduleAmount1').val()/$('#PaymentscheduleExchange').val())).formatCurrency();
                        }
                    }else{
                        $(this).focus();
                        alert('Amount is required');
                        $(this).val($('#PaymentscheduleAmount1').val());
                        $(this).formatCurrency();
                    }
                });
                
                $('#AccountresumeAccountresume').change(function() {
                    $.getJSON('" . Router::url('/admin/paymentschedules/getpaymentdetail/', true) . "'+$('#AccountresumeAccountresume').val(), function(data) {
                        if(data.success) {
                            $('#PaymentschedulePaymentschedule').find('option').remove();
                            for (var key in data.payments) {
                                if (data.payments.hasOwnProperty(key)) {
                                    $('#PaymentschedulePaymentschedule').append('<option value=\"'+key+'\">'+data.payments[key]+'</option>');
                                }
                            }
                            $.getJSON('" . Router::url('/admin/paymentschedules/getplacementdetailtoaih/', true) . "'+$('#PaymentschedulePaymentschedule').first().val(), function(data) {
                                if(data.success) {
                                    $('.sp-payment-aih').html(data.amount);
                                    if(data.paid){
                                        $('#chk-payment-to-aih').attr('checked', true);
                                    }else{
                                        $('#chk-payment-to-aih').removeAttr('checked');
                                    }
                                    if(data.paid_date != ''){
                                        $('#paid-aih-placement-date').val(data.paid_date);

                                    }else{
                                        $('#paid-aih-placement-date').val(aih_date);

                                    }
                                    if(data.paid){
                                        $('#paid-aih-placement-date').attr('style', 'display:inline');
                                    }else{
                                        $('#paid-aih-placement-date').attr('style', 'display:none');
                                    }

                                    $('#chk-payment-to-aih').click(function() {
                                        if($(this).is(':checked')) {
                                            $('#paid-aih-placement-date').attr('style', 'display:inline');
                                        } else {
                                            $('#paid-aih-placement-date').attr('style', 'display:none');
                                        }
                                    });
                                } else {
                                    // error
                                }
                            });
                         $.getJSON('" . Router::url('/admin/paymentschedules/getplacementdetailt/', true) . "'+$('#PaymentschedulePaymentschedule').first().val(), function(data) {
                                if(data.success) {
                                   $('#placemntloop').html('');
                                   $.each(data.data, function(key, value) {
                                        var html = '<div class=\"clearfix\"><span class=\"sp-place1\">To '+ value.contactname+'</span></div>\\n\\
                                        <span class=\"sp-payment-beema-pakistan\">'+ value.contact_amount + '</span>\\n\\
                                        <input type=\"checkbox\" id=\"chk-payment-'+ value.refid +'\" class=\"chk-payment-beema\" name=\"chk-payment-'+ value.refid +'\"><span class=\"sp-paid\">Paid</span>\\n\\
                                        <input id=\"input_date'+value.contact_id+'\" type=\"text\" readonly=\"readonly\" class=\"sel-date-paid sel-date\" name=\"paid_placement_date_'+ value.refid +'\" value=\"'+ value.paid_date +'\"></input>\\n\\
                                        ';
                                        $('#placemntloop').append(html);
                                        if(value.paid){
                                            $('#chk-payment-'+ value.refid +'').attr('checked', true);
                                            $('#input_date'+ value.contact_id +'').val(value.paid_date);
                                            $('#input_date'+ value.contact_id +'').attr('style', 'display:inline');
                                        }else{
                                            $('#chk-payment-'+ value.refid +'').removeAttr('checked');
                                            $('#input_date'+ value.contact_id +'').val(value.paid_date);
                                            $('#input_date'+ value.contact_id +'').attr('style', 'display:none');
                                        }
                                        $('.sel-date-paid').datepicker({ changeYear: true });

                                        $('#chk-payment-'+ value.refid + '').click(function() {
                                            if($(this).is(':checked')) {
                                                $('#input_date'+ value.contact_id +'').attr('style', 'display:inline');
                                            } else {
                                                $('#input_date'+ value.contact_id +'').attr('style', 'display:none');
                                            }
                                        });

                                    });
                                } else {
                                    // error
                                }
                            });
                            $.getJSON('" . Router::url('/admin/paymentschedules/getvalue/', true) . "'+$('#PaymentschedulePaymentschedule').first().val(), function(data) {
                                if(data.success) {
                                    $('#PaymentscheduleDate').html(data.broker_date);
                                    $('#PaymentschedulePayer').html(data.payer);
                                    $('#PaymentschedulePayee').html(data.payee);
                                    $('#payername').val(data.payer);
                                    $('#payeename').val(data.payee);
                                    $('#currencyname').val(data.currency);
                                    $('#PaymentscheduleAmount').val(data.broker_amount - data.paid_amount);
                                    $('#PaymentscheduleAmount1').val(data.broker_amount - data.paid_amount);
                                    if(data.exchange* 1 > 0){
                                        $('#spanpaidamount').html(data.paid_amount/data.exchange);
                                    }else{
                                        $('#spanpaidamount').html(data.paid_amount);
                                    }
                                    $('#spanpaidamount').formatCurrency();
                                    $('#paidamount').val(data.paid_amount);
                                    $('#PaymentscheduleAmount').formatCurrency();
                                    if(data.exchange* 1 > 0){
                                        if(data.exchange_to != null){
                                            $('#paidamountcurrency').html(data.exchange_to);
                                        }else{
                                            $('#paidamountcurrency').html('USD');
                                        }
                                        if(data.exchange_to == 'EURO'){
                                            $('#exchangeto').removeAttr('selected').find('option:contains(\"EURO\")').attr('selected','selected');
                                        }else{
                                            $('#exchangeto').removeAttr('selected').find('option:contains(\"USD\")').attr('selected','selected');
                                        }
                                    }else{
                                        $('#paidamountcurrency').html(data.currency);
                                    }
                                    $('#PaymentscheduleCurrency').html(data.currency);
                                    $('#PaymentscheduleAccountName').val(data.account_name);
                                    $('#PaymentschedulePaymentDesc').val(data.payment_desc);
                                    $('#PaymentscheduleExchange').val(data.exchange);
                                    if(data.exchange * 1 > 0) {
                                        $('#exchangeUSD').html(parseFloat(data.broker_amount/data.exchange)).formatCurrency();
                                    }
                                    if(data.paid_date != ''){
                                        $('#PaymentschedulePaidDate').val(data.paid_date);
                                    }else{
                                        $('#PaymentschedulePaidDate').val(aih_date);
                                    }
                                    if(data.paid){
                                        $('#PaymentschedulePaid').attr('checked', true);
                                        $('#PaymentschedulePaidDate').attr('style', 'display:inline');
                                    }else{
                                        $('#PaymentschedulePaid').removeAttr('checked');
                                        $('#PaymentschedulePaidDate').attr('style', 'display:none');
                                    }
                                    if(data.broker_amount == data.paid_amount){
                                        $('#PaymentscheduleAmount').attr('readonly', 'readonly');
                                    }else{
                                        $('#PaymentscheduleAmount').removeAttr('readonly');
                                    }
                                    if($('#PaymentscheduleExchange').val() * 1 > 0) {
                                        $('#exchangeUSD').html(parseFloat($('#PaymentscheduleAmount1').val()/$('#PaymentscheduleExchange').val())).formatCurrency();
                                    }
                                } else {
                                    // error
                                }
                            });
                        }else{
                            $('#PaymentschedulePaymentschedule').find('option').remove();
                        }
                    });
                });
                
                $('#PaymentscheduleAdminAddForm').ready(function() {
                    $.getJSON('" . Router::url('/admin/paymentschedules/getpaymentdetail/', true) . "'+$('#AccountresumeAccountresume').first().val(), function(data) {
                        if(data.success) {
                            $('#PaymentschedulePaymentschedule').find('option').remove();
                            for (var key in data.payments) {
                                if (data.payments.hasOwnProperty(key)) {
                                    $('#PaymentschedulePaymentschedule').append('<option value=\"'+key+'\">'+data.payments[key]+'</option>');
                                }
                            }
                            $.getJSON('" . Router::url('/admin/paymentschedules/getplacementdetailtoaih/', true) . "'+$('#PaymentschedulePaymentschedule').first().val(), function(data) {
                                        if(data.success) {
                                            $('.sp-payment-aih').html(data.amount);
                                            $('#convertedtoaih').html(data.converted_amount);
                                            $('#rawplacementtoaihamout').val(data.rawamount);
                                            if(data.paid){
                                                $('#chk-payment-to-aih').attr('checked', true);
                                            }else{
                                                $('#chk-payment-to-aih').removeAttr('checked');
                                            }
                                            if(data.paid_date != ''){
                                                $('#paid-aih-placement-date').val(data.paid_date);

                                            }else{
                                                $('#paid-aih-placement-date').val(data.aih_date);

                                            }
                                            if(data.paid){
                                                $('#paid-aih-placement-date').attr('style', 'display:inline');
                                            }else{
                                                $('#paid-aih-placement-date').attr('style', 'display:none');
                                            }

                                            $('#chk-payment-to-aih').click(function() {
                                                if($(this).is(':checked')) {
                                                    $('#paid-aih-placement-date').attr('style', 'display:inline');
                                                } else {
                                                    $('#paid-aih-placement-date').attr('style', 'display:none');
                                                }
                                            });
                                        } else {
                                            // error
                                        }
                                    });
                                 $.getJSON('" . Router::url('/admin/paymentschedules/getplacementdetailt/', true) . "'+$('#PaymentschedulePaymentschedule').first().val(), function(data) {
                                    if(data.success) {
                                       $('#placemntloop').html('');
                                       $.each(data.data, function(key, value) {
                                            var html = '<div class=\"clearfix\"><span class=\"sp-place1\">To '+ value.contactname+'</span></div>\\n\\
                                            <span class=\"sp-payment-beema-pakistan\" id=\"placement-amount-'+ value.refid +'\">'+ value.contact_amount + '</span>\\n\\
                                            <input type=\"hidden\" id=\"raw-placement-amount-'+ value.refid +'\" value=\"'+ value.rawamount +'\" ></input>\\n\\
                                            <input type=\"hidden\" class=\"containrefid\" value=\"'+ value.refid +'\" ></input>\\n\\
                                            <input type=\"checkbox\" id=\"chk-payment-'+ value.refid +'\" class=\"chk-payment-beema\" name=\"chk-payment-'+ value.refid +'\"><span class=\"sp-paid\">Paid</span>\\n\\
                                            <input id=\"input_date'+value.contact_id+'\" type=\"text\" readonly=\"readonly\" class=\"sel-date-paid sel-date\" name=\"paid_placement_date_'+ value.refid +'\" value=\"'+ value.paid_date +'\"></input>\\n\\
                                            <div class=\"clearfix\"><span class=\"sp-payment-beema-pakistan highlight\" id=\"convertedAmoutPlacement'+ value.refid +'\">'+ value.converted_amount + '</span></div>\\n\\
                                            ';
                                            $('#placemntloop').append(html);
                                            if(value.paid){
                                                $('#chk-payment-'+ value.refid +'').attr('checked', true);
                                                $('#input_date'+ value.contact_id +'').val(value.paid_date);
                                                $('#input_date'+ value.contact_id +'').attr('style', 'display:inline');
                                            }else{
                                                $('#chk-payment-'+ value.refid +'').removeAttr('checked');
                                                $('#input_date'+ value.contact_id +'').val(value.paid_date);
                                                $('#input_date'+ value.contact_id +'').attr('style', 'display:none');
                                            }
                                            $('.sel-date-paid').datepicker({ changeYear: true });

                                            $('#chk-payment-'+ value.refid + '').click(function() {
                                                if($(this).is(':checked')) {
                                                    $('#input_date'+ value.contact_id +'').attr('style', 'display:inline');
                                                } else {
                                                    $('#input_date'+ value.contact_id +'').attr('style', 'display:none');
                                                }
                                            });

                                        });
                                    } else {
                                        // error
                                    }
                                });
                                    
                            $.getJSON('" . Router::url('/admin/paymentschedules/getvalue/', true) . "'+$('#PaymentschedulePaymentschedule').first().val(), function(data) {
                                if(data.success) {
                                    $('#PaymentscheduleDate').html(data.broker_date);
                                    $('#PaymentschedulePayer').html(data.payer);
                                    $('#PaymentschedulePayee').html(data.payee);
                                    $('#payername').val(data.payer);
                                    $('#payeename').val(data.payee);
                                    $('#currencyname').val(data.currency);
                                    $('#PaymentscheduleAmount').val(data.broker_amount - data.paid_amount);
                                    $('#PaymentscheduleAmount1').val(data.broker_amount - data.paid_amount);
                                    if(data.exchange* 1 > 0){
                                        $('#spanpaidamount').html(data.paid_amount/data.exchange);
                                    }else{
                                        $('#spanpaidamount').html(data.paid_amount);
                                    }
                                    $('#spanpaidamount').formatCurrency();
                                    $('#paidamount').val(data.paid_amount);
                                    $('#PaymentscheduleAmount').formatCurrency();
                                    if(data.exchange* 1 > 0){
                                        if(data.exchange_to != null){
                                            $('#paidamountcurrency').html(data.exchange_to);
                                        }else{
                                            $('#paidamountcurrency').html('USD');
                                        }
                                        if(data.exchange_to == 'EURO'){
                                            $('#exchangeto').removeAttr('selected').find('option:contains(\"EURO\")').attr('selected','selected');
                                        }else{
                                            $('#exchangeto').removeAttr('selected').find('option:contains(\"USD\")').attr('selected','selected');
                                        }
                                    }else{
                                        $('#paidamountcurrency').html(data.currency);
                                    }
                                    $('#PaymentscheduleCurrency').html(data.currency);
                                    $('#PaymentscheduleAccountName').val(data.account_name);
                                    $('#PaymentschedulePaymentDesc').val(data.payment_desc);
                                    $('#PaymentscheduleExchange').val(data.exchange);
                                    if(data.exchange * 1 > 0) {
                                        $('#exchangeUSD').html(parseFloat(data.broker_amount/data.exchange)).formatCurrency();
                                    }
                                    if(data.paid_date != ''){
                                        $('#PaymentschedulePaidDate').val(data.paid_date);
                                    }else{
                                        //$('#PaymentschedulePaidDate').val(data.broker_date);
                                        var d = new Date();
                                        var twoDigitMonth = ((d.getMonth().length+1) === 1)? (d.getMonth()+1) : '0' + (d.getMonth()+1);
                                        var todaystring = twoDigitMonth + '/' + d.getDate() + '/' + d.getFullYear();
                                        $('#PaymentschedulePaidDate').val(todaystring);
                                    }
                                    if(data.paid){
                                        $('#PaymentschedulePaid').attr('checked', true);
                                        $('#PaymentschedulePaidDate').attr('style', 'display:inline');
                                    }else{
                                        $('#PaymentschedulePaid').removeAttr('checked');
                                        $('#PaymentschedulePaidDate').attr('style', 'display:none');
                                    }
                                    if(data.broker_amount == data.paid_amount){
                                        $('#PaymentscheduleAmount').attr('readonly', 'readonly');
                                    }else{
                                        $('#PaymentscheduleAmount').removeAttr('readonly');
                                    }
                                    if($('#PaymentscheduleExchange').val() * 1 > 0) {
                                        $('#exchangeUSD').html(parseFloat($('#PaymentscheduleAmount1').val()/$('#PaymentscheduleExchange').val())).formatCurrency();
                                    }
                                } else {
                                    // error
                                }
                            });
                        }else{
                            $('#PaymentschedulePaymentschedule').find('option').remove();
                        }
                    });
                });
                
            });";

        return $output;
    }

    public function getcontactJS() {

        $output = "
             $(function() {
                $(function() {
                    $('.checkall').click(function () {
                        if($('#checkflag').val() == '0'){
                            $('.chk-payment-schedule').attr('checked', true);
                            $('#checkflag').val(1);
                            $('.checkall').html('Uncheck All');
                        }else{
                            $('#checkflag').val(0);
                            $('.checkall').html('Check All');
                            $('.chk-payment-schedule').removeAttr('checked');
                        }
                    });
                    $('.chk-payment-schedule').click(function () {
                        if($('.chk-payment-schedule').filter(':not(:checked)').length > 0){
                            $('#checkflag').val(0);
                            $('.checkall').html('Check All');
                        }else{
                            $('#checkflag').val(1);
                            $('.checkall').html('Uncheck All');
                        }
                    });	
                });   
            });
        ";
        return $output;
    }

    public function getPlacementJS() {

        $output = "
             $(function() {
                $('#PaymentschedulePaymentschedule').change(function() {
                    $.getJSON('" . Router::url('/admin/paymentschedules/getplacementdetailtoaih/', true) . "'+$('#PaymentschedulePaymentschedule').val(), function(data) {
                        if(data.success) {
                            $('.sp-payment-aih').html(data.amount);
                            if(data.paid){
                                $('#chk-payment-to-aih').attr('checked', true);
                            }else{
                                $('#chk-payment-to-aih').removeAttr('checked');
                            }
                            if(data.paid_date != ''){
                                $('#paid-aih-placement-date').val(data.paid_date);
                                
                            }else{
                                $('#paid-aih-placement-date').val(data.aih_date);
                            }
                            
                            if(data.paid){
                                $('#paid-aih-placement-date').attr('style', 'display:inline');
                            }else{
                                $('#paid-aih-placement-date').attr('style', 'display:none');
                            }
                            
                            $('#chk-payment-to-aih').click(function() {
                                if($(this).is(':checked')) {
                                    $('#paid-aih-placement-date').attr('style', 'display:inline');
                                } else {
                                    $('#paid-aih-placement-date').attr('style', 'display:none');
                                }
                            });
                            
                        } else {
                            // error
                        }
                    });
                    
                    $.getJSON('" . Router::url('/admin/paymentschedules/getplacementdetailt/', true) . "'+$('#PaymentschedulePaymentschedule').val(), function(data) {
                        if(data.success) {
                           $('#placemntloop').html('');
                           $.each(data.data, function(key, value) {
                                var html = '<div class=\"clearfix\"><span class=\"sp-place1\">To '+ value.contactname+'</span></div>\\n\\
                                <span class=\"sp-payment-beema-pakistan\">'+ value.contact_amount + '</span>\\n\\
                                <input type=\"checkbox\" id=\"chk-payment-'+ value.refid +'\" class=\"chk-payment-beema\" name=\"chk-payment-'+ value.refid +'\"><span class=\"sp-paid\">Paid</span>\\n\\
                                <input id=\"input_date'+value.contact_id+'\" type=\"text\" readonly=\"readonly\" class=\"sel-date-paid sel-date\" name=\"paid_placement_date_'+ value.refid +'\" value=\"'+ value.paid_date +'\"></input>\\n\\
                                ';
                                $('#placemntloop').append(html);
                                if(value.paid){
                                    $('#chk-payment-'+ value.refid +'').attr('checked', true);
                                    $('#input_date'+ value.contact_id +'').val(value.paid_date);
                                    $('#input_date'+ value.contact_id +'').attr('style', 'display:inline');
                                }else{
                                    $('#chk-payment-'+ value.refid +'').removeAttr('checked');
                                    $('#input_date'+ value.contact_id +'').val(value.paid_date);
                                    $('#input_date'+ value.contact_id +'').attr('style', 'display:none');
                                }
                                $('.sel-date-paid').datepicker({ changeYear: true });
                                
                                $('#chk-payment-'+ value.refid + '').click(function() {
                                    if($(this).is(':checked')) {
                                        $('#input_date'+ value.contact_id +'').attr('style', 'display:inline');
                                    } else {
                                        $('#input_date'+ value.contact_id +'').attr('style', 'display:none');
                                    }
                                });
                                
                            });
                        } else {
                            // error
                        }
                    });
                });
            });
        ";
        return $output;
    }

    public function windowMsg() {
        $output = "
            $(function() {
                $('a.revenue_commission').click(function() {
                    var childWin;
                    var ids = '';
                    $('input[name*=\"chk_payment\"]').each(function () {
                        if ($(this).is(':checked')) {
                            ids += (ids=='')? $(this).val() : '-'+$(this).val();
                        }
                    });
                    if(ids!='') {
                        childWin = window.open('" . Router::url('/admin/paymentschedules/report_revenue_commission/', true) . "'+ids, 'child', 'modal,width=1024,height=768,scrollbars=yes');
                    }else{
                        alert('Please select at least one PAYMENT SCHEDULE!')
                    }
                });
                
                $('a.payment_tracking').click(function() {
                    var childWin;
                    var ids = '';
                    $('input[name*=\"chk_payment\"]').each(function () {
                        if ($(this).is(':checked')) {
                            ids += (ids=='')? $(this).val() : '-'+$(this).val();
                        }
                    });
                    if(ids!='') {
                        childWin = window.open('" . Router::url('/admin/paymentschedules/report_payment_tracking/', true) . "'+ids, 'child', 'modal,width=1024,height=768,scrollbars=yes');
                    }else{
                        alert('Please select at least one PAYMENT SCHEDULE!')
                    }
                });
                
                $('a.installment_tracking').click(function() {
                    var childWin;
                    var ids = '';
                    $('input[name*=\"chk_payment\"]').each(function () {
                        if ($(this).is(':checked')) {
                            ids += (ids=='')? $(this).val() : '-'+$(this).val();
                        }
                    });
                    if(ids!='') {
                        childWin = window.open('" . Router::url('/admin/paymentschedules/report_installment_tracking/', true) . "'+ids, 'child', 'modal,width=1024,height=768,scrollbars=yes');
                    }else{
                        alert('Please select at least one PAYMENT SCHEDULE!')
                    }
                });
                
                $('a.payment_schedules').click(function() {
                    var childWin;
                    var ids = '';
                    $('input[name*=\"chk_payment\"]').each(function () {
                        if ($(this).is(':checked')) {
                            ids += (ids=='')? $(this).val() : '-'+$(this).val();
                        }
                    });
                    if(ids!='') {
                        childWin = window.open('" . Router::url('/admin/paymentschedules/report_payment_schedules/', true) . "'+ids, 'child', 'modal,width=1024,height=768,scrollbars=yes');
                    }else{
                        alert('Please select at least one PAYMENT SCHEDULE!')
                    }
                });
                
                $('a.open_trade_account_report').click(function() {
                    var childWin;
                    var ids = '';
                    $('input[name*=\"chk_payment\"]').each(function () {
                        if ($(this).is(':checked')) {
                            ids += (ids=='')? $(this).val() : '-'+$(this).val();
                        }
                    });
                    if(ids!='') {
                        childWin = window.open('" . Router::url('/admin/paymentschedules/report_open_trade_account/', true) . "'+ids, 'child', 'modal,width=1024,height=768,scrollbars=yes');
                    }else{
                        alert('Please select at least one PAYMENT SCHEDULE!')
                    }
                });
            });";

        return $output;
    }

    public function scriptFilter() {
        $output = "
            $(function() {
                $('select#from_to_id').change(function() {
                    var filter1 = $(this).val()==1?'/to:1':'';
//                    var filter1 = '';
//                    if($(this).val()!='') {
//                        filter1 = '/to:'+$(this).val();
//                    }
                    var filter2 = '';
                    if($('select#outstanding_proccessed_id option:selected').val()!='') {
                        filter2 = '/proccessed:'+$('select#outstanding_proccessed_id option:selected').val();
                    }
                    var ids = $('#ids').val();
                    if(ids!='') {
                        window.location.href='" . Router::url('/admin/paymentschedules/report_open_trade_account/', true) . "'+ids+filter1+filter2;
                    }
                });
                
                $('select#outstanding_proccessed_id').change(function() {
                    var filter1 = $('select#from_to_id option:selected').val()==1?'/to:1':'';
//                    var filter1 = '';
//                    if($('select#from_to_id option:selected').val()!='') {
//                        filter1 = '/to:'+$('select#from_to_id option:selected').val();
//                    }
                    var filter2 = '';
                    if($(this).val()!='') {
                        filter2 = '/proccessed:'+$(this).val();
                    }
                    var ids = $('#ids').val();
                    if(ids!='') {
                        window.location.href='" . Router::url('/admin/paymentschedules/report_open_trade_account/', true) . "'+ids+filter1+filter2;
                    }
                });
            });";

        return $output;
    }

    public function scriptSearchBox() {
        $output = "
            $(function() {
                $('#search_button').click(function(){
                    if($('#search_text').val() == ''){
                        $(location).attr('href','" . Router::url('/admin/paymentschedules/search/q:', true) . "' + 'all' + '/paid:'+$('#search_paid').attr('checked')); 
                    }else{
                        $(location).attr('href','" . Router::url('/admin/paymentschedules/search/q:', true) . "' + $('#search_text').val()+ '/paid:'+$('#search_paid').attr('checked'));    
                    }
                });
                $('#search_text').keypress(function(event) {
                    if ( event.which == 13 ) {
                        event.preventDefault();
                        $(location).attr('href','" . Router::url('/admin/paymentschedules/search/q:', true) . "' + $('#search_text').val()+ '/paid:'+$('#search_paid').attr('checked'));
                    }
                });
            });";
        return $output;
    }

}

?>